﻿using System;
using System.Linq;
using Giant.Core;
using Giant.Core.Domain.Sites;
using Giant.Services.Sites;

namespace Giant.Web.Framework
{
    /// <summary>
    /// Site context for web application
    /// </summary>
    public partial class WebSiteContext : ISiteContext
    {
        private readonly ISiteService _siteService;
        private readonly IWebHelper _webHelper;

        private Site _cachedSite;

        public WebSiteContext(ISiteService siteService, IWebHelper webHelper)
        {
            this._siteService = siteService;
            this._webHelper = webHelper;
        }

        /// <summary>
        /// Gets or sets the current site
        /// </summary>
        public virtual Site CurrentSite
        {
            get
            {
                if (_cachedSite != null)
                    return _cachedSite;

                //ty to determine the current site by HTTP_HOST
                var host = _webHelper.ServerVariables("HTTP_HOST");
                var allSites = _siteService.GetAllSites();
                var site = allSites.FirstOrDefault(s => s.ContainsHostValue(host));

                if (site == null)
                {
                    //load the first found site
                    site = allSites.FirstOrDefault();
                }
                if (site == null)
                    throw new Exception("No site could be loaded");

                _cachedSite = site;
                return _cachedSite;
            }
        }
    }
}
